package com.group.itms.routes.services;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.group.itms.routes.activities.UpdateDialogActivity;
import com.group.itms.routes.json.JSONParser;
import com.group.itms.routes.provider.DataProvider;

public class PingService extends IntentService {

	private static final String TAG = "PingService";
	private static final String PING_URL = "http://traces.iliauni.edu.ge/api/check.php?date=";
	
	public static volatile boolean sRunning;
	
	public PingService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		if (!sRunning) {
			ping();
		} else {
			Log.i(TAG, "Ping service is already running");
		}
	}

	private void ping() {
		sRunning = true;
		doPing();
		sRunning = false;
	}
	
	private void doPing() {
		String lastModified = DataProvider.getInstance().lastModified();
		JSONParser parser = JSONParser.getInstance();
		JSONObject updateInfo;
		String url;
		try {
			url = PING_URL + URLEncoder.encode(lastModified, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, "JVM does not support utf-8", e);
			return;
		}
		try {
			updateInfo = parser.parse(url);
		} catch (JSONException e) {
			Log.e(TAG, "Unable to parse json", e);
			return;
		} catch (IOException e) {
			Log.e(TAG, "IOException", e);
			return;
		} catch (Exception e) {
			Log.e(TAG, "Exception", e);
			return;
		}
		int updateCount;
		try {
			updateCount = updateInfo.getInt("update");
		} catch (JSONException e) {
			Log.e(TAG, "Unable to extract int with name "
					 + "update from JSONObject:" + updateInfo, e);
			return;
		}
		if (updateCount > 0) {
			try {
				Thread.sleep(1000); // wait for little time
			} catch (InterruptedException e) {
				
			}
			Intent i = new Intent(this, UpdateDialogActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(i);
			Log.i(TAG, "Available " + updateCount + " new content");
		} else {
			Log.i(TAG, "No new content");
		}
	}
	
}
